"""
路线序列化器
"""
from rest_framework import serializers
from .models import RoutePlan, RouteDistance
from apps.attractions.serializers import AttractionSerializer
from utils.number_formatter import format_price, format_distance


class RoutePlanSerializer(serializers.Serializer):
    """路线规划请求序列化器"""
    budget = serializers.DecimalField(max_digits=8, decimal_places=2)
    start_attraction_id = serializers.IntegerField()
    must_visit = serializers.ListField(
        child=serializers.IntegerField(),
        required=False,
        allow_empty=True
    )
    priority = serializers.ChoiceField(
        choices=['distance', 'cost', 'balanced'],
        default='balanced'
    )
    transport_mode = serializers.ChoiceField(
        choices=[
            ('driving', '自驾'),
            ('transit', '公交'),
            ('bicycling', '骑行'),
            ('walking', '步行'),
        ],
        default='driving',
        required=False
    )
    start_time = serializers.TimeField(
        required=False,
        help_text='开始时间（格式：HH:MM），用于时间约束规划'
    )
    max_total_time = serializers.IntegerField(
        required=False,
        min_value=0,
        help_text='最大总时间（分钟），0表示不限制'
    )


class RoutePlanResponseSerializer(serializers.ModelSerializer):
    """路线规划响应序列化器"""
    start_attraction = AttractionSerializer(read_only=True)
    budget = serializers.SerializerMethodField()
    total_cost = serializers.SerializerMethodField()
    total_distance = serializers.SerializerMethodField()
    is_favorited = serializers.SerializerMethodField()
    favorites_count = serializers.SerializerMethodField()
    
    class Meta:
        model = RoutePlan
        fields = '__all__'
    
    def get_budget(self, obj):
        """格式化预算，保留两位小数"""
        return float(format_price(obj.budget))
    
    def get_total_cost(self, obj):
        """格式化总费用，保留两位小数"""
        return float(format_price(obj.total_cost))
    
    def get_total_distance(self, obj):
        """格式化总距离，保留两位小数"""
        return float(format_distance(obj.total_distance))
    
    def get_is_favorited(self, obj):
        """检查当前用户是否收藏了此路线（优化：避免N+1查询）"""
        # 如果已经通过prefetch_related预加载，直接使用
        if hasattr(obj, 'user_favorites'):
            return len(obj.user_favorites) > 0
        # 否则回退到原始查询（用于单个对象查询）
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            from .models import RouteFavorite
            return RouteFavorite.objects.filter(user=request.user, route_plan=obj).exists()
        return False
    
    def get_favorites_count(self, obj):
        """获取路线收藏数（优化：使用annotate避免N+1查询）"""
        # 如果已经通过annotate预加载，直接使用
        if hasattr(obj, 'favorites_count_annotated'):
            return obj.favorites_count_annotated
        # 否则回退到原始查询（用于单个对象查询）
        return obj.favorited_by.count()


class RouteDistanceSerializer(serializers.ModelSerializer):
    """路线距离序列化器"""
    from_attraction = AttractionSerializer(read_only=True)
    to_attraction = AttractionSerializer(read_only=True)
    
    class Meta:
        model = RouteDistance
        fields = '__all__'

